//
//  NetWorkingHandler.m
//  UI29_Block
//
//  Created by dllo on 16/1/21.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "NetWorkingHandler.h"
#import <CommonCrypto/CommonDigest.h>
#import "Reachability.h"


@implementation NetWorkingHandler

+ (void)handleDataByStr:(NSString *)str body:(NSString *)body header:(NSString *)header block:(void(^)(id result))block  {
    
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:{
            isExistenceNetwork = NO;
            NSLog(@"没网");
            break;
        }
        case ReachableViaWiFi:{
            isExistenceNetwork = YES;
            break;
        }
        case ReachableViaWWAN:{
            isExistenceNetwork = YES;
            break;
        }
    }
    if (isExistenceNetwork) {
        
        
        // 字符串转码
        NSString *codeString = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        
        NSURL *url = [NSURL URLWithString:codeString];
        
        // URLRequest(网络请求对象)
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        request.HTTPMethod = @"POST";
        
        request.HTTPBody = [body dataUsingEncoding:NSUTF8StringEncoding];
        
        [request addValue:header forHTTPHeaderField:@"Content-Type"];
        
        // session对象(通道)
        NSURLSession *sesson = [NSURLSession sharedSession];
        
        // 添加任务
        NSURLSessionDataTask *task = [sesson dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            
            NSString *defaut = @"default/com.hackemist.SDWebImageCache.default/";
            NSString *behind = @".data";
            NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
            
            
            NSString* path =[libPath stringByAppendingPathComponent:[defaut stringByAppendingFormat:@"%@%@",[NetWorkingHandler md5HexDigest:body],behind]];
            
            [data writeToFile:path  atomically:YES];
            
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                NSError *errorJson = nil;
                
                id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&errorJson];
                
                block(result);
                
            });
            
        }];
        
        // 开始任务
        [task resume];
        
    } else {
        
        NSLog(@"没有网络(断网)");
        
        NSString *defaut = @"default/com.hackemist.SDWebImageCache.default/";
        NSString *behind = @".data";
        NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        
        NSString* path =[libPath stringByAppendingPathComponent:[defaut stringByAppendingFormat:@"%@%@",[NetWorkingHandler md5HexDigest:body],behind]];
        
        NSMutableData *data = [NSMutableData dataWithContentsOfFile:path];
        
        if (data == nil) {
            
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"NoNet" object:nil];
            
            return;
            
        } else {
            
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            block(result);
            
        }
        
    }
}

/** md5加密 */
+ (NSString *)md5HexDigest:(NSString*)input {
    const char* str = [input UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (unsigned int)strlen(str), result);
    
    NSMutableString *hash = [NSMutableString string];
    for (int i = 0; i < 16; i++)
    {
        [hash appendFormat:@"%02X", result[i]];
    }
    NSString *mdfiveString = [hash lowercaseString];
    
    return mdfiveString;
    
}









@end
